//
// Created by devink on 8/24/17.
//

#include <sys/time.h>
#include "timeutil.h"
#include <cstring>
using namespace dong ;

int64_t timeutil::getCurremtMs() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    int64_t timestamp = tv.tv_sec * 1000 + tv.tv_usec / 1000;
    return timestamp;
}

std::string timeutil::getStringTime() {

    time_t now = time(NULL);
    struct tm tm_now;
    struct tm* p_tm_now;
    p_tm_now = localtime_r(&now, &tm_now);
    char buff[256] = {0};
    snprintf(buff, sizeof(buff), "%04d-%02d-%02d% 02d:%02d:%02d",
             1900 + p_tm_now->tm_year,
             p_tm_now->tm_mon + 1,
             p_tm_now->tm_mday,
             p_tm_now->tm_hour,
             p_tm_now->tm_min,
             p_tm_now->tm_sec);
    return std::string(buff);
}

time_t timeutil::toTime_t(const std::string &time) {
    tm tm_;
    char buf[128] = { 0 };
    strncpy(buf, time.c_str(), sizeof(buf)-1);
    buf[sizeof(buf) - 1] = 0;
    strptime(buf, "%Y-%m-%d %H:%M:%S", &tm_);
    tm_.tm_isdst = -1;
    return mktime(&tm_);
}

time_t timeutil::getTimeDiff(const std::string &t1, const std::string &t2) {
    time_t time1 = toTime_t(t1);
    time_t time2 = toTime_t(t2);
    time_t dif = time1 - time2;
    return  dif;
}
